<template>
  <a-row :gutter="10">
    <a-modal v-model="showTagModal" title="请选择本次要打的标签" :maskClosable="false" :closable="false" :cancelButtonProps="{ props: { disabled: tags.length > 0 ? false : true }, on: {} }">
      <template v-if="departTree.length > 0 && showTagModal">
        <Tree :treeData="departTree" @updateTags="updateTags" :currentChecked="currentChecked"></Tree>
      </template>
      <template v-else>
        <p>您的部门下暂无有效标签</p>
      </template>
      <div slot="footer">
        <a-button @click="handleCancelTag">取消</a-button>
        <a-button type="primary" @click="handleOkTag">确定</a-button>
      </div>
    </a-modal>
    <a-col :md="24" :sm="24">
      <a-card :bordered="false">
        <template v-if="departTree.length > 0">
          <div>
            <div class="tags-toggle">
              <div class="left">
                <p>所有标签 <a-icon type="right" /></p>
                <div class="tags"></div>
              </div>
              <a-button type="primary" @click="toggleTagModal" class="submit" style="display: block">修改</a-button>
            </div>
            <div class="tags-content" style="max-height: initial">
              <SelectTree :selectTreeData="selectTagsTree"></SelectTree>
            </div>
          </div>
        </template>
        <template v-else>
          <p>您的部门下暂无有效标签</p>
        </template>
      </a-card>
      <a-card :style="{ marginTop: '24px' }">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-col :md="6" :sm="24">
              <a-form-item label="款号">
                <a-input v-model="queryParam.name" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="品牌">
                <a-select v-model="queryParam.brandId" placeholder="请选择" :dropdownStyle="{ zIndex: '5' }" @change="e => handleChangeSelect(e, 'brand')">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option v-for="(item, index) in brandList" :key="index" :value="item.key">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="大类">
                <a-select v-model="queryParam.bigCategoryId" placeholder="请选择" :dropdownStyle="{ zIndex: '5' }" @change="e => handleChangeSelect(e, 'big')">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option v-for="(item, index) in categoryList" :key="index" :value="item.outId">{{ item.title }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="小类">
                <a-select v-model="queryParam.smallCategoryId" default-value="all" placeholder="请选择" :dropdownStyle="{ zIndex: '5' }" @change="e => handleChangeSelect(e, 'small')">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option v-for="(item, index) in scategoryList" :key="index" :value="item.outId">{{ item.title }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="年份">
                <a-select v-model="queryParam.year" placeholder="请选择" default-value="all" :dropdownStyle="{ zIndex: '5' }">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option v-for="(item, index) in yearsList" :key="index" :value="item.attribname">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="波段">
                <a-select v-model="queryParam.bandId" placeholder="请选择" default-value="all" :dropdownStyle="{ zIndex: '5' }">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option v-for="(item, index) in bandsList" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden', marginBottom: 0 }">
                <a-button icon="plus" @click="handleImportXls">导入标签</a-button>
                <a-button type="primary" style="margin-left: 8px" @click="searchList">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
              </span>
            </a-col>
          </a-form>
        </div>
        <div class="ant-pro-pages-list-projects-cardList" style="clear: both">
          <a-list :loading="loading" :data-source="goodsList" :grid="{ xxl: 8, xl: 6, lg: 4, md: 3, sm: 2, xs: 1 }">
            <div v-if="showLoadingMore" slot="loadMore" :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }">
              <a-spin v-if="loadingMore" />
              <a-button v-else @click="onLoadMore"> loading more </a-button>
            </div>
            <a-list-item slot="renderItem" slot-scope="item, index">
              <a-card class="ant-pro-pages-list-projects-card" hoverable>
                <img
                  slot="cover"
                  :src="item.skus[0].imgurl ? item.skus[0].imgurl : 'https://img.bzhz.jnbygroup.com/cloth.png'"
                  :alt="item.value"
                  v-if="item.skus.length > 0"
                  @click="toDetail(item, index)"
                />
                <img slot="cover" :alt="item.value" src="https://img.bzhz.jnbygroup.com/cloth.png" v-else @click="toDetail(item)" />
                <p>款号：{{ item.name }}</p>
                <div class="cardItemContent">
                  <h3>{{ item.value }}</h3>
                  <p class="red">吊牌价:¥{{ item.price }}.00</p>
                  <!-- <p>销量：{{ item.sales_num }}</p>
                    <p>{{ item.colorno }}/{{ item.color_name }}</p>
                    <p class="blue">库存：{{ item.currentSku.stock }}</p>
                    <div class="size-box">
                      <a-radio-group v-model="item.currentSku.sizeno" button-style="solid" @change="e=>sizeChange(e,index)">
                        <a-radio-button :value="sizeItem.sizeno" v-for="(sizeItem,sizeIndex) in item.skus" :key="sizeIndex" :id="sizeItem.id">
                          {{ sizeItem.size_name }}
                        </a-radio-button>
                      </a-radio-group>
                    </div> -->
                </div>
                <div class="btn">
                  <a-button type="primary" icon="plus" :loading="item.iconLoading" @click="addGoodsTags(item, index)" block></a-button>
                </div>
              </a-card>
            </a-list-item>
          </a-list>
        </div>
      </a-card>
    </a-col>
    <GoodsDetailDrawer :goodsInfo="goodsInfo" :showDrawer="showDrawer" @close="close"></GoodsDetailDrawer>
    <EditGoodsTagsModal ref="modalGoods" :treeData="selectTagsTree" @updateEdit="updateEdit" :currentTotal="currentTotal" :total="total" @loadingPage="loadingPage"></EditGoodsTagsModal>
    <j-import-modal ref="importModal" :url="getImportUrl()" :uploadParams="getUploadParams()" @ok="importOk" :templateUrl="templateUrl()" :serviceId="4"></j-import-modal>
  </a-row>
</template>
<script>
import { queryDim, queryCatePermisListByDepart, queryGoods, querySelCatePerByDepart, queryCatePermisListByIds } from '@/api/goods'
import GoodsDetailDrawer from './modules/GoodsDetailDrawer'
import Tree from './modules/Tree'
import SelectTree from './modules/SelectTree'
import EditGoodsTagsModal from './modules/EditGoodsTagsModal'
import { queryUploadSuccess } from '@/assets/js/common'
import globalData from '@/assets/js/common'
import JImportModal from '@/components/qiniuUpload/JImportModal'

export default {
  components: {
    GoodsDetailDrawer,
    Tree,
    SelectTree,
    EditGoodsTagsModal,
    JImportModal
  },
  data() {
    return {
      departTree: [],
      tags: [],
      checked: [],
      updateChecked: [],
      currentChecked: [],
      selectTagsTree: [],
      queryParam: {
        brandId: 'all',
        bigCategoryId: 'all',
        smallCategoryId: 'all',
        year: 'all',
        bandId: 'all',
        mustNotLabels: []
      },
      brandList: [],
      categoryList: [],
      scategoryList: [],
      yearsList: [],
      bandsList: [],
      loading: false,
      loadingMore: false,
      showLoadingMore: false,
      goodsList: [],
      pageSize: 20,
      current: 1,
      total: 0,
      pages: 0,
      currentTotal: 0,
      goodsInfo: {},
      showDrawer: false,
      showGoodsTags: false,
      showTagModal: true,
      timer: null
    }
  },
  mounted() {
    this.getSelectList()
    this.getCate()
    // const params = JSON.parse(JSON.stringify(this.queryParam))
    // this.fetchList(params)
  },
  beforeDestroy() {
    // 页面销毁后同时清除定时器，避免占用内存
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    // 获取商品筛选条件
    getSelectList() {
      queryDim().then(res => {
        if (res.code === 0) {
          this.bandsList = res.data.bands
          this.yearsList = res.data.years
          // this.categoryList = res.data.categoryTrees
          // this.scategoryList = this.categoryList[0].childCategory
          this.brandList = res.data.categoryTrees[0].brands
        } else {
          this.$message.warning(res.data.msg)
        }
      })
    },
    // 获取可选择标签
    getCate() {
      let params = {
        code: 'B05'
      }
      queryCatePermisListByDepart(params).then(res => {
        if (res.success) {
          // this.departTree = res.result
          if (res.result.length > 0) {
            this.departTree = res.result.map(item => {
              const checked = {
                checked: [],
                checkedName: []
              }
              return { ...item, ...checked }
            })
            console.log(this.departTree)
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 筛选标签范围
    updateTags(value) {
      this.updateChecked = value
      // console.log(this.updateChecked)
    },
    onChange(checkedValues, item) {
      console.log('checked = ', checkedValues)
      // console.log(item)
      /* let arr = []
      let checkedName = []
      let children = item.children
      if (checkedValues.length > 0) {
        for (var i = 0; i < children.length; i++) {
          if (children[i].leaf) {
            // 叶子
            const result = checkedValues.filter(item => item == children[i].key)
            if (result.length > 0) {
              checkedName.push(children[i].title)
              arr.push(children[i])
            }
          } else {
            const nextChildren = children[i].children
            // 非叶子
            for (var j = 0; j < nextChildren.length; j++) {
              const result = checkedValues.filter(item => item == nextChildren[j].key)
              if (result.length > 0) {
                checkedName.push(nextChildren[j].title)
                arr.push(nextChildren[j])
              }
            }
          }
        }
        item.checkedName = checkedName
        // console.log(arr)
        // 有选中标签
        if (checkedName.length > 0) {
          const obj = {
            title: item.title,
            tag: checkedName,
            content: checkedName.join(','),
            arr:arr
          }
          // console.log(obj)
          if (this.tags.length == 0) {
            this.tags.push(obj)
          } else {
            let index = this.tagIndex(obj, this.tags)
            if (index != -1) {
              this.tags[index] = obj
            } else {
              this.tags.push(obj)
            }
          }
        }
        // console.log(item.checkedName)
      } else {
        const title = item.title
        const resetTags = this.tags.filter(item => item.title !== title)
        this.tags = resetTags
        item.checkedName = []
      }
      console.log(this.tags) */
    },
    tagIndex(obj, arr) {
      let tagIndex = -1
      for (var a = 0; a < arr.length; a++) {
        if (arr[a].title == obj.title) {
          tagIndex = a
          return tagIndex
          break
        }
      }
      return tagIndex
    },
    // 删除筛选条件中的标签
    handleClose(removedTag, index) {
      // console.log(removedTag,index)
      const tags = this.tags.filter(tag => tag.title !== removedTag.title)
      this.tags = tags
      for (var i = 0; i < this.departTree.length; i++) {
        if (removedTag.title == this.departTree[i].title) {
          this.departTree[i].checkedName = []
          this.departTree[i].checked = []
          break
        }
      }
      console.log(this.tags)
      // console.log(this.departTree)
    },
    // 修改筛选的tags
    editTags() {
      console.log(this.checked)
      if (this.checked.length > 0) {
        this.queryParam.mustNotLabels = this.checked
      } else {
        this.queryParam.mustNotLabels = []
      }
    },
    // 处理勾选tag
    getTagArr(tags) {
      console.log(tags)
      let allTagsPare = this.departTree.map(item => item.code)
      let arr = []

      for (var i = 0; i < allTagsPare.length; i++) {
        let item = allTagsPare[i]
        let trr = []
        trr = tags.filter(value => {
          if (value.indexOf(item) > -1) {
            return value
          }
        })
        if (trr.length > 0) {
          arr.push({
            pidCode: item,
            codes: trr
          })
        }
      }

      console.log(arr)
      return arr
    },
    // 选择要打的标签
    handleOkTag() {
      if (this.departTree.length > 0) {
        if (this.updateChecked.length > 0) {
          this.currentChecked = JSON.parse(JSON.stringify(this.updateChecked))
          const data = this.getTagArr(this.updateChecked)
          this.querySelectTags(data)
          this.queryCatePermisList(data)
          this.queryParam.mustNotLabels = this.currentChecked
          this.searchList()
        } else {
          this.$message.warning('请选择标签！')
        }
      } else {
        this.$router.back(-1)
      }
    },
    // 查询勾选的打标范围
    querySelectTags(data) {
      let params = {
        code: 'B05',
        selectedSysCateCode: data
      }
      console.log(params)
      querySelCatePerByDepart(params).then(res => {
        if (res.success) {
          this.selectTagsTree = res.result
          this.showTagModal = false
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 获取标签对应的商品类目
    queryCatePermisList(data) {
      let params = {
        code: 'B06',
        selectedSysCateCode: data
      }
      queryCatePermisListByIds(params).then(res => {
        if (res.code == 0) {
          this.categoryList = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    toggleTagModal() {
      this.showTagModal = true
      console.log(this.currentChecked)
    },
    // 关闭打标签范围弹窗
    handleCancelTag() {
      if (this.departTree.length > 0) {
        if (this.currentChecked.length > 0) {
          this.showTagModal = false
        } else {
          this.$router.back(-1)
          // this.$message.warning('请选择标签！')
        }
      } else {
        this.$router.back(-1)
      }
    },
    // 筛选条件
    handleChangeSelect(value, type) {
      console.log(value, type)
      switch (type) {
        case 'big':
          const option = this.categoryList.filter(item => {
            if (item.outId === value) {
              return item
            }
          })
          this.scategoryList = option[0].children
          this.queryParam.smallCategoryId = 'all'
          break
      }
    },
    // 搜索
    searchList() {
      this.current = 1
      this.goodsList = []
      const param = JSON.parse(JSON.stringify(this.queryParam))
      this.fetchList(param)
    },
    // 重置
    resetList() {
      this.queryParam = {
        brandId: 'all',
        bigCategoryId: 'all',
        smallCategoryId: 'all',
        year: 'all',
        bandId: 'all',
        mustNotLabels: []
      }
      this.tags = []
      /*       for(var i=0;i<this.departTree.length;i++){
        this.departTree[i].checked=[]
        this.departTree[i].checkedName=[]
      } */
      this.searchList()
    },
    // 加载更多
    onLoadMore() {
      this.loadingMore = true
      this.current += 1
      const param = JSON.parse(JSON.stringify(this.queryParam))
      this.fetchList(param)
    },
    fetchList(param) {
      if (param.brandId === 'all') {
        delete param.brandId
      }
      if (param.bigCategoryId === 'all') {
        delete param.bigCategoryId
      }
      if (param.smallCategoryId === 'all') {
        delete param.smallCategoryId
      }
      if (param.year === 'all') {
        delete param.year
      }
      if (param.bandId === 'all') {
        delete param.bandId
      }
      if (param.name) {
        param = {
          name: param.name
        }
      }
      let data = {
        page: {
          pageNo: this.current,
          pageSize: this.pageSize
        },
        requestData: param
      }
      queryGoods(data).then(res => {
        if (res.code == 0) {
          if (res.data.length > 0) {
            this.current = res.page.pageNo
            this.total = res.page.count
            this.pages = res.page.pages
            this.currentTotal = this.current * this.pageSize
            console.log(this.currentTotal)
            const dataList = res.data
            this.goodsList = this.goodsList.concat(dataList)
            if (res.page.pageNo < res.page.pages) {
              this.showLoadingMore = true
            } else {
              this.showLoadingMore = false
            }
            this.loading = false
            this.loadingMore = false
          } else {
            this.showLoadingMore = false
          }
        }
      })
    },
    // 查看商品详情
    toDetail(item, index) {
      console.log(item, index)
      // this.$router.push(`/goods/detail/${item.id}`)
      this.goodsInfo = {
        productId: item.id,
        index: index
      }
      console.log(this.goodsInfo)
      this.showDrawer = true
    },
    // 关闭goodsDetail
    close(value) {
      this.showDrawer = false
    },
    // 编辑商品标签
    addGoodsTags(item, index) {
      this.$refs.modalGoods.add(item, index)
    },
    // 编辑商品标签：prev & next
    updateEdit(index) {
      this.$refs.modalGoods.add(this.goodsList[index], index)
    },
    // 编辑商品下一个到当前页的最后一个时，加载下一页
    loadingPage(value) {
      if (value) {
        this.onLoadMore()
      }
    },
    // 导入
    handleImportXls() {
      this.$refs.importModal.show()
    },
    // 处理上传业务的后台地址
    getImportUrl() {
      return ''
    },
    getUploadParams() {
      // console.log({...globalData.uploadParams})
      return { ...globalData.uploadParams }
    },
    // 上传成功后的方法
    importOk(result) {
      let that = this
      queryUploadSuccess(this.timer, result, 60000, function (x) {
        console.log(x)
        if (x == 'done' || x == 'warning') {
          that.$refs.importModal.close()
        }
      })
    },
    templateUrl() {
      return 'https://img.bzhz.jnbygroup.com/product/productLabelSample.xlsx'
    }
  }
}
</script>
<style lang="less" scoped>
@import './less/index.less';
</style>

